/**
 * HolySet
 */
package patrolclient;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * @author <a href="mailto:guangzong@gmail.com">Guangzong Syu</a>
 *
 */
public class Config {

	public static final String PROTOCOL = "protocol";
	public static final String HOST = "host";
	public static final String PORT = "port";
	public static final String APP = "app";

	private File file = new File("config.ini");
	private FileInputStream fis;
	private Properties p;

	public Config() {
		if(!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		try {
			fis = new FileInputStream(file);
			p = new Properties();
			p.load(fis);
			fis.close();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e2) {
			e2.printStackTrace();
		}
	}

	public void saveConfig() {
		if(!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		try {
			FileOutputStream fos = new FileOutputStream(file);
			p.store(fos, null);
			fos.close();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e2) {
			e2.printStackTrace();
		}
	}

	public void set(String key, String value) {
		p.put(key, value);
	}

	public String get(String key) {
		String value = (String) p.get(key);
		if(value == null) {
			value = "";
		}
		return value;
	}

	public String getFullApplicationUrl() {
		StringBuilder url = new StringBuilder();
		url.append(get(PROTOCOL));
		url.append("://");
		url.append(get(HOST));
		url.append(":");
		url.append(get(PORT));
		url.append(get(APP));
		return url.toString();
	}
}
